import type { ResolvedConfig, Plugin } from 'vite'
import { resolve } from 'node:path'
import { getDirectorySize, formatBytes } from './utils'
import gradient from 'gradient-string'
import boxen, { type Options as BoxenOptions } from 'boxen'
import dayjs, { type Dayjs } from 'dayjs'
import duration from 'dayjs/plugin/duration.js'
dayjs.extend(duration)

// const gradientMessage = gradient(["cyan", "magenta"]).multiline(
//     `从今以后我只能称呼你为您了，因为，你在我心上。\n疯狂Coding......`
// )

const boxenOptions: BoxenOptions = {
    padding: 0.5,
    borderColor: "cyan",
    borderStyle: "round"
}


// type VoidFunc = () => void
// type PluginOptions = VoidFunc | string | Plugin


export default function vueSloganPlugin(): Plugin {
    let config: ResolvedConfig;
    let startTime: Dayjs;
    let endTime: Dayjs;
    let outDir: string;

    return {
        name: 'vite-plugin-output',
        // configResolved: 在解析 Vite 配置后调用。使用这个钩子读取和存储最终解析的配置
        configResolved(resolvedConfig: ResolvedConfig){
            config = resolvedConfig;
            outDir = resolvedConfig.build?.outDir ?? "dist";
        },
        // Rollup 的钩子
        buildStart() {
            // console.log(boxen(gradientMessage, boxenOptions))
            if (config.command === 'build') {
                startTime = dayjs(new Date())
            }
        },
        // Rollup的钩子
        closeBundle() {
            // 只有在打包，运行 build 命令才生效;
            if (config.command === 'build') {
                endTime = dayjs(new Date())
                const takeTime = dayjs.duration(endTime.diff(startTime))
                const m = takeTime.get('minutes')
                const s = takeTime.get('second')
                const S = takeTime.get('milliseconds')
                try {
                    const distPath = resolve(process.cwd(), outDir || 'dist')
                    const totalBytes = getDirectorySize(distPath)
                    const size = formatBytes(totalBytes)
                    console.log(boxen(
                        gradient(["cyan", "magenta"]).multiline(
                            `🎉🎉 恭喜打包完成,总用时: ${m}分${s}秒${S}毫秒 🎉🎉, 打包后的大小为 ${size}`
                        ),
                        boxenOptions
                    ))
                } catch (e) {
                    throw e
                }
            }
        }
    }
}
